package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

/**
 * 订单管量
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;

    //生成结算号
    @GetMapping("/auth/trade")
    public Result trade(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        String tradeNo = UUID.randomUUID().toString();
        //保存结算号的Key
        String key = "user:" + userId + ":tradeNo";
        //保存此tradeNo 到缓存中
        redisTemplate.opsForValue().set(key,tradeNo);
        return Result.ok(tradeNo);
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo,String tradeNo,HttpServletRequest request){
        //1:防止二次提交
        String userId = AuthContextHolder.getUserId(request);
        //保存结算号的Key
        String key = "user:" + userId + ":tradeNo";

        String tradeNo1 = (String) redisTemplate.opsForValue().get(key);
        if(StringUtils.isEmpty(tradeNo1)){
            return Result.fail().message("不要重复提交订单");
        }else{
            if(!tradeNo1.equalsIgnoreCase(tradeNo)){
                return Result.fail().message("不要重复提交订单");
            }
        }
        //代码到此处的时候 证明结算号是正确的 防止 二次提交  应该在此处删除结算号
        redisTemplate.delete(key);
        //2:验证库存   如果无库存 提交用户  某某款商品的名称：无货
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            //每一款商品都验证库存
            boolean isStock = orderInfoService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if(!isStock){
                //无货
                return Result.fail().message(orderDetail.getSkuName() + ":库存不足");
            }
        }
        //3：保存订单 返回值 订单ID
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.saveOrderInfo(orderInfo);
        return Result.ok(orderId);
    }

    //根据订单Id查询订单信息
    @GetMapping("/getOrderInfo/{orderId}")
    public Result getOrderInfo(@PathVariable(name = "orderId") Long orderId){
        OrderInfo orderInfo = orderInfoService.getOrderInfo(orderId);
        return Result.ok(orderInfo);
    }
    //根据订单Id查询订单信息
    @GetMapping("/getOrderInfoById/{orderId}")
    public OrderInfo getOrderInfoById(@PathVariable(name = "orderId") Long orderId){
       return orderInfoService.getOrderInfo(orderId);
    }
}
